package com.example.userservice.config;

import com.example.userservice.entity.User;
import com.example.userservice.feign.PermissionServiceClient;
import com.example.userservice.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicLong;

@Component
@RequiredArgsConstructor
@Slf4j
public class DataInitializer implements CommandLineRunner {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final PermissionServiceClient permissionServiceClient;
    private final AtomicLong idGenerator = new AtomicLong(System.currentTimeMillis() + 1000); // 确保ID唯一

    @Override
    public void run(String... args) {
        if (userMapper.findByUsername("super_admin").isEmpty()) {
            User superAdmin = new User();
            long userId = idGenerator.incrementAndGet();
            superAdmin.setUserId(userId);
            superAdmin.setUsername("super_admin");
            superAdmin.setPassword(passwordEncoder.encode("password")); // 默认密码,生产环境请务必修改
            superAdmin.setEmail("superadmin@example.com");
            superAdmin.setPhone("12345678900");
            superAdmin.setGmtCreate(LocalDateTime.now());
            
            userMapper.save(superAdmin);
            log.info("用户 'super_admin' 创建成功。");

            try {
                permissionServiceClient.bindRole(userId, "super_admin");
                log.info("成功为用户 'super_admin' 绑定 SUPER_ADMIN 角色。");
            } catch (Exception e) {
                log.error("为用户 'super_admin' 绑定角色失败。", e);
            }
        }
    }
} 